package com.joysuch.wwyt.api.sync.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.api.sync.SyncJobUtil;
import com.joysuch.wwyt.api.sync.SyncResponse;
import com.joysuch.wwyt.api.sync.bean.BaseSyncUserBean;
import com.joysuch.wwyt.api.sync.service.BaseSyncUserService;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpEnterpriseInfo;
import com.joysuch.wwyt.bp.entity.BpWorkType;
import com.joysuch.wwyt.bp.repository.BpEnterpriseInfoDao;
import com.joysuch.wwyt.bp.repository.BpWorkTypeDao;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.bp.service.BpWorkTypeService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class BaseSyncUserServiceImpl implements BaseSyncUserService {

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BpDepartService departService;

    @Autowired
    private BpWorkTypeService workTypeService;

    @Autowired
    private BaseUserDao baseUserDao;

    @Autowired
    private BpWorkTypeDao workTypeDao;

    @Autowired
    private BpEnterpriseInfoDao enterpriseInfoDao;

    @Autowired
    private LocateServerService locateServerService;

    @Override
    public ResultBean syncUserInfo() {
        log.info("人员列表同步Job 开始 ...");
        Set<String> bukrs = SyncConstants.unitCodeMap.keySet();
        List<String> msgList = new ArrayList<>();
        for(String companyCode: bukrs){
            try {
                ResultBean result = syncUserByCompany(companyCode);
                msgList.add(result.getData().toString());
            }catch(Exception e){
                log.error("人员列表同步出错： companyCode={}",companyCode,e);
            }
        }
        log.info("人员列表同步Job 结束 ...");
        return ResultBean.success(msgList);
    }

    @Override
    public ResultBean syncUserByCompany(String companyCode) {

        BaseConfig config = baseConfigService.findConfig(SyncConstants.TENENT_ID_DEFAULT, companyCode, SyncConstants.BASE_CONFIG_USER_LIST_URL);
        if (config != null && StringUtils.isNotEmpty(config.getValue())) {
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.APPLICATION_JSON);
            //set request body
            HttpEntity<String> requestBody = new HttpEntity<String>(companyCode, header);
            log.info("人员列表同步Job：url={}, param={}", config.getValue());

            SyncResponse response = restTemplate.postForObject(config.getValue(), requestBody, SyncResponse.class);
            if (response.getMsgcode().equals("0")) {
                if (response.getData() == null) {
                    log.info("人员列表同步Job： 获取数据列表为空， URL={}", config.getValue());
                    return ResultBean.success("人员列表同步完成：  共同步0条记录；");
                }
                String data = JSONObject.toJSONString(response.getData());

                JSONObject content = JSONObject.parseObject(data);
               Integer count= processList(content.getString("content"), companyCode);


                return ResultBean.success("人员列表同步结束： 共同步" + count.toString() + "条记录；" );
            } else {
                log.error("人员列表同步Job： 接口数据获取失败： {}", response);
                return ResultBean.success("人员列表同步失败：  接口数据获取失败；");
            }
        }
        return ResultBean.success("人员列表同步失败：  同步接口未配置；");

    }


    // 人员信息处理
        private Integer processList (String content, String companyCode){
           if(content == null){
               return 0;
           }
            List<BaseSyncUserBean> list = JSONArray.parseArray(content, BaseSyncUserBean.class );
            log.info(".... 人员同步Job： 共查询列表 list:{} ....", list.size());
            Map<String, Long> departMap = getDepartMap();
            Map<String, Long> jobMap = getJobMap();
            Map<String, Long> companyMap = getCompanyMap();
            Long departId;
            Long workTypeId;
            List<BaseUser> userList = new ArrayList<>();
            int count = 0;
            List<BaseUser> syncList = new ArrayList<>();
            for(BaseSyncUserBean bean: list){
                if(bean.getOrgCode() == null || !companyCode.equals(bean.getOrgCode())){
                    continue;
                }

                BaseUser user = baseUserDao.findByCodeAndCompanyCode(bean.getCode(),bean.getOrgCode());
                if(user == null){
                    user = new BaseUser();
                    user.setCode(bean.getCode());
                    user.setDeleteFlag("0");
                    user.setState(1);
                    user.setTenentId(SyncConstants.TENENT_ID_DEFAULT);
                    user.setOrgCode(bean.getOrgCode());
                    //获取部门
                    departId = departMap.get(bean.getOrgCode()+bean.getDepartName());
                    //没有匹配的部门名称，则放在顶级部门(公司）
                    if(departId == null){
                        departId = departMap.get(bean.getOrgCode());
                    }
                    user.setDepartId(departId);
                    // 工种
                    if(StringUtils.isNotEmpty(bean.getJobName())){
                        workTypeId =jobMap.get(bean.getOrgCode()+bean.getJobName());
                        if(workTypeId == null){
                            workTypeId = createNewWorkType(bean.getJobName(),bean.getOrgCode());
                            jobMap.put(bean.getOrgCode()+bean.getJobName(), workTypeId);
                        }
                        user.setWorkTypeId(workTypeId);
                    }
                    user.setRole(bean.getRole());
                    //所属公司
                    user.setWorkCompanyId(companyMap.get(bean.getOrgCode()));

                    user.setRealName(bean.getRealName());
                    user.setRefUrl(bean.getRefUrl());
                    user.setSn(bean.getSn());
                    user.setCardNumber(bean.getCardNumber());
                    user.setFacePic(bean.getFacePic());
                    user.setCapId(1L);
                    user.setLocateSync(false);
                    count ++;
                    userList.add(user);
                }else{
                    if(SyncJobUtil.checkIfDifferent(user.getRefUrl(), bean.getRefUrl())
                            || SyncJobUtil.checkIfDifferent(user.getSn(), bean.getSn())
                            || SyncJobUtil.checkIfDifferent(user.getFacePic(), bean.getFacePic())
                            || SyncJobUtil.checkIfDifferent(user.getCardNumber(), bean.getCardNumber())
                            || SyncJobUtil.checkIfDifferent(user.getDepartId(), departMap.get(bean.getOrgCode()+bean.getDepartName()))
                            || SyncJobUtil.checkIfDifferent(user.getWorkTypeId(), jobMap.get(bean.getOrgCode()+bean.getJobName()))){
                        user.setRefUrl(bean.getRefUrl());
                        user.setSn(bean.getSn());
                        user.setCardNumber(bean.getCardNumber());
                        user.setFacePic(bean.getFacePic());
                        //获取部门
                        departId = departMap.get(bean.getOrgCode()+bean.getDepartName());
                        //没有匹配的部门名称，则放在顶级部门(公司）
                        if(departId == null){
                            departId = departMap.get(bean.getOrgCode());
                        }
                        user.setDepartId(departId);
                        //工种
                        if(StringUtils.isNotEmpty(bean.getJobName())){
                            workTypeId =jobMap.get(bean.getOrgCode()+bean.getJobName());
                            if(workTypeId == null){
                                workTypeId = createNewWorkType(bean.getJobName(),bean.getOrgCode());
                                jobMap.put(bean.getOrgCode()+bean.getJobName(), workTypeId);
                            }
                            user.setWorkTypeId(workTypeId);
                        }
                        if(user.getCapId() == null){
                            user.setCapId(1L);
                        }

                        count++;
                        userList.add(user);
                    }
                }


                //批量更新， 每100 个更新一批
                if(userList.size() >=100){
                    log.info(".... 人员同步Job： 已同步人员列表 list:{} ....", userList.size());
                    baseUserDao.saveAll(userList);
                    //调用接口，同步到人员在岗在位系统
                    syncList = userList.stream().filter(it-> StringUtils.isNotEmpty(it.getSn())).collect(Collectors.toList());
                    if(!syncList.isEmpty()){
                        locateServerService.syncLocateUsers(syncList,0);
                        syncList = Collections.EMPTY_LIST;
                    }

                    userList =  Collections.EMPTY_LIST;

                }
            }
            if(userList.size() >0){
                log.info(".... 人员同步Job： 已同步人员列表 list:{} ....", userList.size());
                baseUserDao.saveAll(userList);
                syncList = userList.stream().filter(it-> StringUtils.isNotEmpty(it.getSn())).collect(Collectors.toList());
                if(!syncList.isEmpty()){
                    locateServerService.syncLocateUsers(syncList,0);
                }

            }

            return count;
        }



    private Map<String, Long> getDepartMap(){
        Map<String, Long> departMap = new HashMap<>();
        List<BpDepart> list = departService.findAllDepartByTenentId(SyncConstants.TENENT_ID_DEFAULT);
        if(list != null){
            for(BpDepart d: list){
                if(d.getParentId() == null){
                    departMap.put(d.getOrgCode(),d.getId());
                }else{
                    departMap.put(d.getOrgCode()+d.getName(), d.getId());
                }

            }
        }
        return departMap;
    }

    private Map<String, Long> getJobMap(){
        Map<String, Long> map = new HashMap<>();
        List<BpWorkType> list = workTypeService.findAllByTenentId(SyncConstants.TENENT_ID_DEFAULT);
        if(list != null){
            for(BpWorkType d: list){
                map.put(d.getOrgCode()+d.getName(), d.getId());
            }
        }
        return map;
    }


    private Long createNewWorkType(String workTypeName, String orgCode){
        BpWorkType workType = new BpWorkType();
        workType.setDeleteFlag("0");
        workType.setOrgCode(orgCode);
        workType.setName(workTypeName);
        workType.setTenentId(SyncConstants.TENENT_ID_DEFAULT);
       workType = workTypeDao.save(workType);
       return workType.getId();
    }


    private Map<String, Long> getCompanyMap(){
        Map<String, Long> map = new HashMap<>();
        List<BpEnterpriseInfo> list = enterpriseInfoDao.findAllByTenentId(SyncConstants.TENENT_ID_DEFAULT);
        if(list != null){
            for(BpEnterpriseInfo d: list){
                map.put(d.getOrgCode(), d.getId());
            }
        }
        return map;
    }

}